package com.shilei.c04_1_Interview;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @description:   2个生产者  10个消费者 问题
 * @author: 81271
 * @date: 2020-06-20 12:13
 */
public class MyContainer1<T> {
    final private LinkedList<T> lists = new LinkedList<>();
    final private int MAX = 10;
    private int count = 0;

    public synchronized void put(T t) {
        while(lists.size() == MAX) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        lists.add(t);
        count ++;
        this.notifyAll();
    }

    public synchronized T get() {
        while(lists.size() == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count --;
        this.notifyAll();
        return lists.removeFirst();
    }


    public static void main(String[] args) {
        MyContainer1<String> c = new MyContainer1<>();

        //消费者
        for(int i=0; i<10; i++) {
            new Thread(()->{
                for(int j=0; j<5; j++) {
                    System.out.println(Thread.currentThread().getName() + " "  + c.get());
                }
            }, "c" + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //生产者
        for(int i=0; i<2; i++) {
            new Thread(()->{
                for(int j=0; j<25; j++) {
                    c.put(Thread.currentThread().getName() + " " + j);
                    System.out.println(Thread.currentThread().getName() + " " + j);
                }
            }, "p" + i).start();
        }
    }
}
